<template>
  <div class="container">
    <el-row class="header">
      <el-col :span="10" align="left">
        <el-input
          clearable
          icon="el-icon-search"
          v-model="data.params.projectName"
          placeholder="项目名称/项目编号"
          style="width: 220px; margin-right: 15px"
        />
        <el-button class="ordinary" @click="search()">搜索</el-button>
      </el-col>
      <el-col :span="14" align="right">
        <el-button v-limit="'XMZX:ZXGL:JFGL:EXPORT'" class="ordinary" @click="exportExcel()"
          >批量导出</el-button
        >
        <el-button v-limit="'XMZX:ZXGL:JFGL:VALUE'" type="primary" @click="handleContractValue()"
          >同步合同产值</el-button
        >
        <el-button v-limit="'XMZX:ZXGL:JFGL:COUNT'" type="primary" @click="handleSubpackage()"
          >同步分包计量</el-button
        >
        <el-button v-limit="'XMZX:ZXGL:JFGL:COST'" type="primary" @click="handleCostControl()"
          >同步智慧费控</el-button
        >
      </el-col>
    </el-row>

    <Table
      :loading="data.isLoading"
      :tableArr="data.allTableData"
      :columns="data.columns"
      :page-size="data.params.size"
      :page-num="data.params.current"
      @selectList="getCurrentList"
      @row-click="handleRowClick"
    >
      <template #operate="{ row }">
        <el-button v-limit="'XMZX:ZXGL:JFGL:DETAIL'" class="ordinary" @click="handleDetail(row)"
          >详情</el-button
        >
      </template>
    </Table>
    <div class="example-pagination-block">
      <el-pagination
        background
        layout="prev, pager, next ,total,sizes,jumper"
        :total="data.total"
        :page-size="data.params.size"
        v-model:current-page="data.params.current"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      />
    </div>
    <el-dialog v-model="data.syncDialog" width="60%" title="选择同步项目">
      <syncProject ref="syncDialog" v-if="data.syncDialog"></syncProject>
      <template #footer>
        <el-button @click="data.syncDialog = false">关闭</el-button>
        <el-button type="primary" @click="handleSync">确认同步</el-button>
      </template>
    </el-dialog>
    <el-dialog top="10vh" v-model="data.detailDialog" width="72%" title="经费详情">
      <fundingDetails v-if="data.detailDialog"></fundingDetails>
      <template #footer>
        <el-button @click="data.detailDialog = false">关闭</el-button>
      </template>
    </el-dialog>
    <!-- 导出字段选择 -->
    <Export
      :detailList="data.detailList"
      :showing="data.exportDialog"
      @close="closeExport"
      @handle-filed="handleFiled"
    ></Export>
  </div>
</template>

<script lang="ts">
import { reactive, ref } from 'vue'
import tableData from './tableHeader.json'
import {
  getProductList,
  syncPackage,
  syncContract,
  syncCostControl,
  getExportExcel,
  getDetailById,
} from '../../api/money-manage'
import Export from '@/views/project/components/Export/index.vue'
import Table from '../../components/table2/table.vue'
import syncProject from './components/sync-project.vue'
import fundingDetails from './components/funding-details.vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import JSEncrypt from '@/utils/jsencrypt'
import { ZZ_PUBLIC_KEY, ZZ_PRIVATE_KEY } from '@/constants'
import { servicesLoading } from '@/views/project/project-manage/loading'
import { useStore } from 'vuex'

export default {
  components: {
    Table,
    syncProject,
    fundingDetails,
    Export,
  },
  setup() {
    const store = useStore()
    let data = reactive({
      params: {
        projectName: '',
        current: 1,
        size: 10,
      },
      total: 0,
      isLoading: false,
      allTableData: [],
      columns: tableData.platformTableHeader,
      ids: [],
      syncDialog: false,
      detailDialog: false,
      currentList: [],
      currentHandle: '',
      exportDialog: false,
      detailList: [] as any,
    })
    const syncDialog = ref()
    const search = () => {
      data.params.current = 1
      onSearch()
    }
    const onSearch = () => {
      data.isLoading = true
      getProductList(data.params).then((res) => {
        console.log(res, 'getProductList')
        data.allTableData = res.data.data.records
        data.total = res.data.data.total
        data.isLoading = false
      })
    }
    onSearch()
    const getCurrentList = (currentList) => {
      console.log(currentList, 'getCurrentList')
      data.currentList = currentList
      data.ids = currentList.map((item) => {
        return item.id
      })
    }
    const handleContractValue = () => {
      data.syncDialog = true
      data.currentHandle = '合同产值'
    }
    const handleSubpackage = () => {
      data.syncDialog = true
      data.currentHandle = '分包计量'
    }
    const handleCostControl = () => {
      data.syncDialog = true
      data.currentHandle = '智慧费控'
    }
    const syncContractValue = (params) => {
      const loading = servicesLoading({ fullscreen: true })
      if (data.currentHandle == '合同产值') {
        syncContract(params)
          .then((res) => {
            loading.close()
            console.log(res, 'syncContract')
            if (res.data.code == 200) {
              ElMessage({
                message: '同步成功',
                type: 'success',
              })
              onSearch()
              data.syncDialog = false
            }
          })
          .catch(() => {
            loading.close()
          })
      } else if (data.currentHandle == '分包计量') {
        syncPackage(params)
          .then((res) => {
            loading.close()
            console.log(res, 'syncContract')
            if (res.data.code == 200) {
              ElMessage({
                message: '同步成功',
                type: 'success',
              })
              onSearch()
              data.syncDialog = false
            }
          })
          .catch(() => {
            loading.close()
          })
      } else if (data.currentHandle == '智慧费控') {
        syncCostControl(params)
          .then((res) => {
            loading.close()
            console.log(res, 'syncCostControl')
            if (res.data.code == 200) {
              ElMessage({
                message: '同步成功',
                type: 'success',
              })
              onSearch()
              data.syncDialog = false
            }
          })
          .catch(() => {
            loading.close()
          })
      }
    }
    const handleSync = () => {
      let projectList = syncDialog.value.hasChoose()
      console.log(projectList, 'projectList')
      if (projectList.length > 0) {
        let projectIds = projectList
          .map((item) => {
            return item.id
          })
          .join(',')
        let projectICodes = projectList
          .map((item) => {
            return item.primaryDataNumber
          })
          .join(',')
        console.log(projectIds, projectICodes)

        let ZhongziConfig = reactive(store.state.projectCenter.ZhongziConfig)
        // let ZhongziConfig = {} as any
        let ciphertext = encryption({
          appcode: ZhongziConfig.appcode,
          username: ZhongziConfig.username,
          password: ZhongziConfig.password,
          projectCodes: projectICodes,
          // appcode: 'KG',
          // username: 'kg',
          // password: 'kg$zhzz1024',
          // projectCodes: 'RP2023025287,RP2023022468'
        })
        console.log(ciphertext, '密文')
        decrypt(ciphertext)
        let params = {
          projectId: projectIds,
          cipherText: ciphertext,
        }
        syncContractValue(params)
      } else {
        ElMessage({
          message: '请至少选择一个项目',
          type: 'warning',
        })
      }
    }
    const handleRowClick = (row) => {
      handleDetail(row)
    }
    const handleDetail = (row) => {
      console.log(row, 'handleDetail')
      getDetailById(row.projectId).then((res) => {
        if (res.data.code == 200) {
          store.state.projectCenter.fundingDetails = res.data.data
          console.log(store.state.projectCenter.fundingDetails, '获取经费详情')
          data.detailDialog = true
        } else {
          ElMessage({
            message: '查询失败',
            type: 'warning',
          })
        }
      })
    }
    //改变页码
    const handleCurrentChange = (e) => {
      console.log(e, 'handleCurrentChange')
      data.params.current = e
      onSearch()
    }
    //改变页数限制
    const handleSizeChange = (e) => {
      console.log(e, 'handleSizeChange')
      data.params.size = e
      onSearch()
    }
    const closeExport = () => {
      data.exportDialog = false
    }
    const handleFiled = (arr) => {
      console.log(arr, 'handleFiled')
      if (arr.length > 0) {
        ElMessageBox.confirm('您确认导出查询数据吗？', '批量导出', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          getExportExcel({ ...data.params, ids: data.ids, headList: arr })
          console.log('批量导出')
          data.exportDialog = false
        })
      }
    }
    const exportExcel = () => {
      data.exportDialog = true
      data.detailList = [
        { fieldName: 'projectName', title: '项目名称' },
        { fieldName: 'projectId', title: '项目编码' },
        { fieldName: 'allAmount', title: '总产值(元)' },
        { fieldName: 'finishAmount', title: '已完成产值(元)' },
        { fieldName: 'subpackageAmount', title: '分包计量总额(元)' },
        { fieldName: 'finishSubpackageAmount', title: '已完成分包计量(元)' },
        { fieldName: 'totalProjectBudget', title: '项目总预算(元)' },
        { fieldName: 'disbursedAmount', title: '经费已支出(元)' },
      ]
    }
    // const exportExcel = () => {
    //   ElMessageBox.confirm('您确认导出查询数据吗？', '批量导出', {
    //     confirmButtonText: '确认',
    //     cancelButtonText: '取消',
    //     type: 'warning',
    //   }).then(() => {
    //     getExportExcel({ ...data.params, ids: data.ids })
    //   })
    // }
    //加密方法
    const encryption = (params) => {
      console.log(params, '加密之前')
      const encrypt = new JSEncrypt()
      encrypt.setPublicKey(ZZ_PUBLIC_KEY)
      const encryptPassword = encrypt.encrypt(JSON.stringify(params))
      console.log(encryptPassword, '加密之后')
      return encryptPassword
    }
    // 解密方法
    const decrypt = (params) => {
      const decrypt = new JSEncrypt()
      decrypt.setPrivateKey(ZZ_PRIVATE_KEY)
      const encryptPassword = decrypt.decrypt(params)
      console.log(encryptPassword, '解密之后')
      return encryptPassword
    }
    return {
      data,
      syncDialog,
      exportExcel,
      closeExport,
      handleFiled,
      search,
      onSearch,
      handleContractValue,
      handleSubpackage,
      handleCostControl,
      handleSync,
      handleDetail,
      handleRowClick,
      getCurrentList,
      handleCurrentChange,
      handleSizeChange,
    }
  },
}
</script>

<style lang="scss" scoped>
.container {
  background-color: white;
  padding: 20px;
}
</style>
